package org.tao.lightningmq.broker.core;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tao.lightningmq.broker.cache.CommonCache;
import org.tao.lightningmq.broker.model.MqTopicModel;
import org.tao.lightningmq.broker.model.QueueModel;
import org.tao.lightningmq.common.enums.FileSizeUnitEnum;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author lht
 * @date 2025/1/4 - 21:45
 * @description:
 */
public class ConsumeQueueAppendHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(ConsumeQueueAppendHandler.class);

    public void prepareConsumeQueue(String topic) throws Exception {
        MqTopicModel mqTopicModel = CommonCache.getMqTopicModelMap().get(topic);
        List<QueueModel> queueList = mqTopicModel.getQueueList();
        if (queueList == null) return;
        List<ConsumeQueueMMapFileModel> consumeQueueMMapFileModelList = new ArrayList<>();
        for (QueueModel queueModel : queueList) {
            ConsumeQueueMMapFileModel consumeQueueMMapFileModel = new ConsumeQueueMMapFileModel();
            consumeQueueMMapFileModel.loadFileMMap(
                    topic,
                    queueModel.getId(),
                    queueModel.getLastOffset(),
                    queueModel.getLatestOffset().get(),
                    queueModel.getOffsetLimit(),
                    FileSizeUnitEnum.B);
            consumeQueueMMapFileModelList.add(consumeQueueMMapFileModel);
        }
        CommonCache.getConsumeQueueMMapFileModelManager().put(topic, consumeQueueMMapFileModelList);
    }
}
